package com.deepclassifieds.daas.common.sql;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SQLExecutor<T> {

	private static final Logger logger = LoggerFactory.getLogger(SQLExecutor.class);

	private final ConnectionProvider connectionProvider;
	
	public SQLExecutor(ConnectionProvider connectionProvider) {
		this.connectionProvider = connectionProvider;
	}
	
	public T execute(SQLTask<T> sqlTask) {
		Connection connection = null;
		try {
	    	connection = connectionProvider.getConnection();
	    	return sqlTask.execute(connection);
		} catch(SQLException ex) {
			throw new RuntimeException(
					"SQL exception, see nested...", ex);
		} finally {
			if (connection != null) {
		    	try {
					connection.close();
				} catch (SQLException ex) {
					logger.error("Cannot close connection, see nested...", ex);
				}
			}
		}
		
	}

}
